package org.example.zookeeper.config;

import com.alibaba.fastjson.JSONObject;
import com.zaxxer.hikari.HikariDataSource;
import org.example.zookeeper.service.SwitchDatasourceService;
import org.example.zookeeper.zk.ZookeeperRegistryCenter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DatasourceConfig {

    @Bean
    public ZookeeperRegistryCenter zookeeperRegistryCenter() {
        ZookeeperRegistryCenter zookeeperRegistryCenter = new ZookeeperRegistryCenter();
        zookeeperRegistryCenter.init();
        return zookeeperRegistryCenter;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(ZookeeperRegistryCenter zookeeperRegistryCenter) throws Exception{
        String path = "/";
        String datasource = zookeeperRegistryCenter.getDirectly(path);
        JSONObject jsonObject = JSONObject.parseObject(datasource);
        String driverClass = jsonObject.getString("driverClass");
        String jdbcUrl = jsonObject.getString("jdbcUrl");
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName(driverClass);
        hikariDataSource.setJdbcUrl(jdbcUrl);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);

        JdbcTemplate jdbcTemplate = new JdbcTemplate(hikariDataSource);
        return jdbcTemplate;
    }

    @Bean
    public SwitchDatasourceService switchDatasourceService(ZookeeperRegistryCenter zookeeperRegistryCenter,
                                                           JdbcTemplate jdbcTemplate) {
        SwitchDatasourceService switchDatasourceService =
                new SwitchDatasourceService(zookeeperRegistryCenter, jdbcTemplate);
        return switchDatasourceService;
    }
}
